<template>
  <el-container class="layout-container-demo">
    <!-- 侧边栏 -->
    <el-aside :width="asideWidth">
      <div class="title">
        <img class="project-logo" src="@/assets/logo.svg" />
        <h2 class="project-name">后台管理系统</h2>
      </div>
      <el-menu :default-active="$route.path" router background-color="#001529" text-color="rgba(255,255,255,0.65)"
        active-text-color="#ffffff" :collapse-transition="false" :unique-opened="true" :collapse="isCollapse">
        <template v-for="menu in userMenus" :key="menu.id">
          <!-- 有子菜单的情况 -->
          <el-sub-menu v-if="menu.children && menu.children.length > 1" :index="menu.id!.toString()">
            <template #title>
              <el-icon>
                <component :is="getMenuIcon(menu.icon)" />
              </el-icon>
              <span class="menu-title">{{ menu.name }}</span>
            </template>
            <el-menu-item class="menu-item" v-for="subMenu in menu.children" :key="subMenu.id" :index="subMenu.path">
              {{ subMenu.name }}
            </el-menu-item>
          </el-sub-menu>
          <!-- 没有子菜单的情况 -->
          <el-menu-item v-else :index="menu.path">
            <el-icon>
              <component :is="getMenuIcon(menu.icon)" />
            </el-icon>
            <span class="menu-title">{{ menu.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header>
        <div class="left">
          <el-icon style="margin-right: 16px; font-size: large" @click="handleCollapse">
            <component :is="collapseIcon" />
          </el-icon>
          <el-icon style="margin-right: 16px; font-size: large" @click="refreshPage">
            <RefreshRight />
          </el-icon>
          <!-- 动态面包屑 -->
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index"
              :to="item.path ? { path: item.path } : undefined">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="right">
          <el-icon style="margin-right: 16px; font-size: large" @click="handleFulls">
            <FullScreen />
          </el-icon>
          <el-icon style="margin-right: 16px; font-size: large">
            <Setting />
          </el-icon>
          <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            style="margin-right: 16px"></el-avatar>
          <el-button @click="logout" type="danger" size="small">退出</el-button>
        </div>
      </el-header>
      <!-- 主体内容 -->
      <el-main>
        <el-scrollbar>
          <router-view />
        </el-scrollbar>
      </el-main>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import {
  House,
  Upload,
  Cpu,
  Bell,
  Tickets,
  Odometer,
  Monitor,
  Fold,
  Expand,
  RefreshRight,
  FullScreen,
  Setting,
  User,
} from '@element-plus/icons-vue'
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { MenuItem } from '@/api/menu'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

//加载内存里面的菜单
const { userMenus } = storeToRefs(userStore)

// 面包屑数据
const breadcrumbList = ref<Array<{ title: string; path?: string }>>([])

// 根据图标名称获取图标组件
const getMenuIcon = (iconName?: string) => {
  const iconMap: Record<string, object> = {
    'HomeOutlined': House,
    'DashboardOutlined': Odometer,
    'ClusterOutlined': Cpu,
    'AlertOutlined': Bell,
    'HddOutlined': Tickets,
    'LaptopOutlined': Monitor,
    'LinkOutlined': Upload,
    'UserOutlined': User,
  }
  return iconMap[iconName || ''] || House
}

// 刷新页面
const refreshPage = () => {
  window.location.reload()
}

// 折叠侧边栏
const isCollapse = ref(false)
const asideWidth = ref('200px')
// 根据折叠状态动态选择图标
const collapseIcon = computed(() => {
  return isCollapse.value ? Expand : Fold
})
const handleCollapse = () => {
  isCollapse.value = !isCollapse.value
  asideWidth.value = isCollapse.value ? '64px' : '200px'
  const projectName = document.querySelector('.project-name') as HTMLElement
  projectName.style.display = isCollapse.value ? 'none' : 'inline-block'
}

// 查找菜单完整路径信息
const findMenuTitleByPath = (path: string, menus: MenuItem[]):  {current: MenuItem | null, parent: MenuItem | null
} => {
  for (const menu of menus) {
    if (menu.path === path.replace("/", "")) {
      return { current: menu, parent: null }
    }
    if (menu.children && menu.children.length > 0) {
      for (const childMenu of menu.children) {
        if (childMenu.path === path.replace("/", "")) {
          return { current: childMenu, parent: menu }
        }
      }
    }
  }
  return { current: null, parent: null }
}

const generateBreadcrumb = () => {
  const currentPath = route.path
  const breadcrumbs: Array<{ title: string; path?: string }> = []

  // 根据路径生成面包屑
  const { current, parent } = findMenuTitleByPath(currentPath, userMenus.value)

  if (parent) {
    // 有父级菜单的情况：显示 父菜单 / 子菜单
    breadcrumbs.push({
      title: parent.name,
      path: `/${parent.path}`
    })
  }

  if (current) {
    // 当前菜单（不可点击）
    breadcrumbs.push({
      title: current.name,
      path: undefined
    })
  } else {
    // 找不到菜单时显示默认控制台
    breadcrumbs.push({ title: '控制台' })
  }
  breadcrumbList.value = breadcrumbs
}
// 查找当前菜单及其父级信息
const findCurrentMenu = (menus: any[], targetPath: string, parentName?: string): any => {
  for (const menu of menus) {
    if (menu.path === targetPath) {
      return { ...menu, parentName }
    }
    if (menu.children) {
      const found = findCurrentMenu(menu.children, targetPath, menu.name)
      if (found) return found
    }
  }
  return null
}
// 格式化面包屑标题
const formatBreadcrumbTitle = (path: string): string => {
  const titleMap: Record<string, string> = {
    'dashboard': '控制台',
    'screenpreview': '画面预览',
    'screenediting': '画面编辑',
    'projectlist': '项目列表',
    'picture': '画面文件',
    'drive': '驱动列表',
    'device': '通讯设备',
    'devicevariable': '通讯变量',
    'alarmstrategy': '报警条件',
    'alarmdata': '报警数据',
    'historystoragestrategy': '存储条件',
    'historydata': '历史数据',
    'computevariable': '计算变量',
    'executewhere': '执行条件',
    'holdingvariable': '保持变量',
    'computescript': '脚本计算',
    'httpconfig': 'HTTP转发',
    'mqttconfig': 'MQTT转发',
    'modbustcpservice': 'Modbus转发',
    'log': '操作日记',
    'role': '角色管理',
    'menu': '菜单管理',
    'user': '用户管理'
  }
  return titleMap[path.toLowerCase()] || path.charAt(0).toUpperCase() + path.slice(1)
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    generateBreadcrumb()
  },
  { immediate: true }
)

// 全屏
const handleFulls = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    document.documentElement.requestFullscreen()
  }
}

// 退出
const logout = () => {
  userStore.clearUserInfo()
  localStorage.removeItem('token')
  router.push('/login')
}

// 初始化
onMounted(() => {
  generateBreadcrumb()
  console.log('用户菜单数据:', userMenus.value)
  userMenus.value.forEach(menu => {
    console.log(`菜单: ${menu.name}, 图标: ${menu.icon}`)
    if (menu.children) {
      menu.children.forEach(child => {
        console.log(`子菜单: ${child.name}, 图标: ${child.icon}`)
      })
    }
  })
})
</script>

<style scoped>
.layout-container-demo {
  min-height: 100vh;
  min-width: 100vw;
}

.el-aside {
  background-color: #001529;
  transition: width 0.2s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  color: #ffffff;
}

.title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.project-logo {
  width: 30px;
  height: 30px;
  margin-right: 5px;
}

.project-name {
  color: #ffffff;
  font-size: 16px;
}

.layout-container-demo .el-header {
  border-bottom: 1px solid var(--el-border-color-light);
  display: inline-flex;
  justify-content: space-between;
}

.layout-container-demo .el-menu {
  border: none;
}

.layout-container-demo .el-main {
  background-color: #f5f7f9;
  padding: 10px;
}

.layout-container-demo .right,
.layout-container-demo .left {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

:deep(.el-breadcrumb__inner) {
  color: var(--el-text-color-regular);
}

:deep(.el-breadcrumb__inner:hover) {
  color: var(--el-color-primary);
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: var(--el-text-color-primary);
  font-weight: bold;
}
</style>
